<?php


namespace app\admin\model;


use app\sys\model\Conn;
use app\sys\model\Dict;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Log;
use think\Model;
use think\model\concern\TimeStamp;

class ChatLog extends Model
{
    protected $autoWriteTimestamp = true;
    /**
     * 发送给客服
     */
    const SEND_TO_STAFF = 'staff';
    /**
     * 发送给用户
     */
    const SEND_TO_USER = 'user';
    /**
     * 系统发送
     */
    const SEND_TO_SYS = 'sys';

    public static function add($store, $id, $user, $staff, $data, $agent, $sendToNo, $seUidNo, $staffNo, $userNo)
    {
        $createDay = strtotime(date("Y-m-d"), time());
        $createMon = strtotime(date("Y-m"), time());


        $no = substr($seUidNo, 4);
        // 获取站点
        $hostUrl = getComeUrl();
        $site = Dict::getValue("site", $hostUrl);
        // 添加记录
        $chatType = 0;
        $storeId = 0;
        if ($store) {
            $chatType = 1; // 店铺消息
            $storeId = UserPvLog::where("pxs_id", $store)->order("id desc")->value("id", 0);
        }

        $log = [
            "chat_type" => $chatType,
            "chat_id" => $id,
            "user_id" => $user,
            "store_id" => $storeId,
            "staff_id" => $staff,
            "info" => $data,
            "user_agent" => $agent,
            "send_to" => $sendToNo,
            "create_day" => $createDay,
            "create_mon" => $createMon,
            "site_value" => $site
        ];

        $log_count = ChatLog::field("conn_count,chat_log_count,chat_id")
            ->where("user_id", $user)->where("staff_id", $staff)->where("send_to", $sendToNo)
            ->order("create_time desc")->find();
        $con_count = Conn::where("no", $no)->where("device_type", $agent)->value("conn_count", 0);
        // 1.没有
        // 2.相等
        // 3.不相等

        // conn_count 绑定次数   chat_log_count 聊天次数 talk_no 会话标识
        // talk_no 通过 用户绑定次数  与 聊天 的绑定次数 相同  说明在同一个对话
        if (isset($log_count) && $con_count == $log_count["conn_count"]) {
            $log["chat_log_count"] = $log_count["chat_log_count"];
        } else if (isset($log_count) && $con_count > $log_count["conn_count"]) {
            $log["chat_log_count"] = $log_count["chat_log_count"] + 1;
            // 对话数据添加
            Chat::where("id", $log_count["chat_id"])->data(["chat_count" => $log["chat_log_count"]])->update();

            // 发起提示语
            $sendType = "";
            if ($sendToNo == "staff") {
                $sendType = "用户发起";
            } else if ($sendToNo == "user") {
                $sendType = "客服发起";
            }
            chat::TisToUser($user, $staff, 0, $sendType);
        } else {
            $log["chat_log_count"] = 1;

            // 发起提示语
            $sendType = "";
            if ($sendToNo == "staff") {
                $sendType = "用户发起";
            } else if ($sendToNo == "user") {
                $sendType = "客服发起";
            }
            chat::TisToUser($user, $staff, 0, $sendType);
        }

        $log["conn_count"] = $con_count;
        // 获取talk_no v1.1.1 废除 由客服手动生成
//        $log["talk_no"] = self::getTalkNo($user,$staff,$agent);
        $log["talk_no"] = "";
        // 回复统计数据
        StaffReplyTime::add($staffNo, $userNo, $agent, $log["talk_no"], $sendToNo);

        Log::info("ChatLog" . json_encode($log));
        return ChatLog::create($log);
    }

    /**
     * 无逻辑
     * @param $store
     * @param $id
     * @param $user
     * @param $staff
     * @param $data
     * @param $agent
     * @param $sendToNo
     * @param $seUidNo
     * @param $staffNo
     * @param $userNo
     */
    public static function addLes($store, $id, $user, $staff, $data, $agent, $sendToNo, $seUidNo, $staffNo, $userNo): ChatLog
    {
        $createDay = strtotime(date("Y-m-d"), time());
        $createMon = strtotime(date("Y-m"), time());

        $no = substr($seUidNo, 4);
        // 获取站点
        $hostUrl = getComeUrl();
        $site = Dict::getValue("site", $hostUrl);
        // 添加记录
        $chatType = 0;
        $storeId = 0;
        if ($store) {
            $chatType = 1; // 店铺消息
            $storeId = UserPvLog::where("pxs_id", $store)->order("id desc")->value("id", 0);
        }

        $log = [
            "chat_type" => $chatType,
            "chat_id" => $id,
            "user_id" => $user,
            "store_id" => $storeId,
            "staff_id" => $staff,
            "info" => $data,
            "user_agent" => $agent,
            "send_to" => $sendToNo,
            "create_day" => $createDay,
            "create_mon" => $createMon,
            "site_value" => $site,
            "status" => 1
        ];

        Log::info("addLes" . json_encode($log));
        return ChatLog::create($log);
    }

    /**
     * 获取同一会话的talk_no（ v1.1.1 废除 由客服手动生成）
     * @param $user
     * @param $staff
     * @param $agent
     * @return mixed|string
     */
    public static function getTalkNo($user, $staff, $agent)
    {
        $talkNo = time() . rand(10, 100);
        // 以客户的会话为标准
        $log_count = ChatLog::field("conn_count,talk_no")
            ->where("user_id", $user)->where("staff_id", $staff)->where("send_to", "staff")
            ->order("create_time desc")->find();

        $con_count = User::alias("u")
            ->leftJoin("ic_conn ic", "ic.no = u.no")->where("u.id", $user)->where("ic.device_type", $agent)->value("conn_count");

        // talk_no 通过 用户绑定次数  与 聊天 的绑定次数 相同  说明在同一个对话
        if (isset($log_count) && $con_count == $log_count["conn_count"]) {
            $talkNo = $log_count["talk_no"];
        }
        return $talkNo;
    }

    /**
     * 获取同一会话的talk_no
     * @param $user
     * @param $staff
     * @param $chatId
     * @return mixed|string
     */
    public static function setTalkNoAct($user, $staff, $chatId): string
    {
        $resC = ChatLog::field("conn_count,talk_no")->where("chat_id", $chatId)
            ->where("user_id", $user)->where("staff_id", $staff)->where("talk_no", '')->find();
        if (!$resC) {
            return "对话已结束~";
        }
        $talkNo = time() . rand(10, 100);
        $res = ChatLog::field("conn_count,talk_no")->where("chat_id", $chatId)
            ->where("user_id", $user)->where("staff_id", $staff)->where("talk_no", '')->data(["talk_no" => $talkNo])->update();
        if (!$res) return "失败~";
        return "";
    }
}